<template>
  <div>
    <Row>
      <Col span="12">
        <div class="top-button-group">
          <Button @click="showDistributeAccess" class="top-button">权限分配</Button>
          <Button @click="showAddGroup" class="top-button">添加组</Button>
          <Button @click="showAddPassport" class="top-button">添加账号</Button>
          <Button icon="md-refresh" @click="reloadList"></Button>
        </div>
      </Col>
    </Row>
    <Table title="权限分配" :data="tableData" :columns="columns" :loading="loading"/>
    <Modal :value="distributeAccessVisible"
           :loading="true"
           @on-cancel="closeDistributeAccess"
           title="查看&编辑权限"
           :mask-closable="false">
      <div>
        <Select size="small" style="width:50%;margin-bottom: 10px;display: inline-block;" placeholder="请选择组..."
                @on-change="changeSelectedGroup" v-model="selectedGroup"
                filterable clearable @on-clear="clearSelectedGroup">
          <Option v-for="group in groups" :value="group.id" :label="group.name" :key="group.id"></Option>
        </Select>
      </div>
      <div style="text-align:justify;overflow-x: hidden;">
        <CheckboxGroup v-model="accessCheckGroup">
          <div v-bind:key="item.id" v-for="item in menus" style="width: 50%;display:inline-block">
            <Checkbox :key="item.id" :value="item.id" :label="item.id" :disabled="selectedGroup === ''">
              {{item.subTypeName}}
            </Checkbox>
          </div>
        </CheckboxGroup>
      </div>
      <div slot="footer">
        <Button @click="closeDistributeAccess">取消</Button>
        <Button type="primary" @click="submitDistributeAccess" :loading="submitDistributeAccessLoading">保存</Button>
      </div>
    </Modal>

    <Modal title="添加组"
           :value="addGroupVisible"
           :mask-closable="false"
           @on-cancel="closeAddGroup">
      <Form ref="addGroup" :label-width="100">
        <FormItem label="输入新的组名:">
          <Input size="small" v-model="newGroupName" type="text"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="closeAddGroup">取消</Button>
        <Button type="primary" @click="submitAddGroup" :loading="submitAddGroupLoading">保存</Button>
      </div>
    </Modal>

    <Modal title="添加账号" :value="addPassportVisible" @on-cancel="closeAddPassport">
      <Form ref="addPassport" :label-width="80">
        <FormItem label="用户名:">
          <Input v-model="newUserName" type="text"></Input>
        </FormItem>
        <FormItem label="密码:">
          <Input v-model="newPwd" type="password"></Input>
        </FormItem>
        <FormItem label="是否禁用:">
          <RadioGroup v-model="newUserBaned">
            <Radio :label="0">
              <Icon type="md-checkmark-circle"/>
              <span>启用</span>
            </Radio>
            <Radio :label="1">
              <Icon type="md-close-circle"/>
              <span>禁用</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="选择权限组:">
          <Select style="width:50%;margin-bottom: 10px;display: inline-block;"
                  @on-change="changeSelectedGroup"
                  v-model="selectedGroup"
                  filterable clearable>
            <Option v-for="group in groups" :value="group.id" :label="group.name" :key="group.id"></Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="closeAddPassport">取消</Button>
        <Button type="primary" @click="submitAddPassport" :loading="submitAddPassportLoading">保存</Button>
      </div>
    </Modal>
    <Modal title="修改密码" :value="changePwdVisible" @on-cancel="closeChangePwd">
      <Form ref="changePwd" :label-width="100">
        <FormItem label="输入旧密码:">
          <Input v-model="oldPwd" type="password"></Input>
        </FormItem>
        <FormItem label="输入新密码:">
          <Input v-model="newPwd" type="password"></Input>
        </FormItem>
        <FormItem label="确认新密码:">
          <Input v-model="newPwdConfirm" type="password"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="closeChangePwd">取消</Button>
        <Button type="primary" @click="submitChangePwd(selectedUser.accountName)" :loading="submitAddGroupLoading">保存
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {getPassports, getMenuAccess, setGroupAccess, getGroups} from '@/api/access-control'

  import {addGroup, addUser, updatePwd} from '@/api/access-control'

  export default {
    name: 'distribute-access',
    data() {
      return {
        loading: false,
        tableData: [],
        distributeAccessVisible: false,
        menus: [],
        accessCheckGroup: [],
        groups: [],
        newGroupName: '',
        addGroupVisible: false,
        addPassportVisible: false,
        newUserBaned: 1,
        changePwdVisible: false,
        oldPwd: '',
        newPwd: '',
        newPwdConfirm: '',
        newUserName: '',
        selectedGroup: '',
        submitDistributeAccessLoading: false,
        submitAddGroupLoading: false,
        submitAddPassportLoading: false,
        submitUpdatePwdLoading: false,
        selectedUser: {},
        columns: [
          {
            title: '账号',
            key: 'accountName'
          },
          {
            title: '所属权限组',
            key: 'groupName'
          },
          {
            title: '是否禁用',
            key: 'useAble',
            render: (h, param) => {
              return h('span', param.row.banned === 1 ? '是' : '否')
            }
          },
          {
            title: '操作',
            key: 'operation',
            render: (h, param) => {
              return h('Button', {
                on: {
                  click: () => {
                    this.selectedUser = param.row
                    this.showChangePwd()
                  }
                }
              }, '修改密码')
            }
          }
        ]
      }
    },
    methods: {
      initData() {
        this.getMenuItem()
        this.getGroups()
        this.reloadList()
      },
      reloadList() {
        this.loading = true
        getPassports().then(response => {
          if (response.data === null) {
            this.tableData = []
            this.loading = false
            return
          }
          this.tableData = response.data
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      showDistributeAccess() {
        this.getGroups()
        this.distributeAccessVisible = true
      },
      closeDistributeAccess() {
        this.selectedGroup = ''
        this.accessCheckGroup = []
        this.distributeAccessVisible = false
      },
      submitDistributeAccess() {
        this.submitDistributeAccessLoading = true
        const selectedGroupEntity = this.groups.filter(group => group.id === this.selectedGroup)[0]
        console.log(selectedGroupEntity)
        const oldAccess = selectedGroupEntity.operation
        const addedAccess = this.accessCheckGroup.filter(item => !oldAccess.includes(item))
        const removedAccess = oldAccess.filter(item => !this.accessCheckGroup.includes(item))
        const addGroupAccessTO = {
          id: this.selectedGroup,
          addedAccess: addedAccess,
          removedAccess: removedAccess
        }
        setGroupAccess(addGroupAccessTO).then(response => {
          this.submitDistributeAccessLoading = false
          if (response.status === 200) {
            this.$Message.success('设置权限组成功')
            this.closeDistributeAccess()
          } else {
            this.$Message.error('设置权限组失败:' + response.message)
          }
        }).catch(() => {
          this.$Message.error('未知错误')
          this.submitDistributeAccessLoading = false
        })
      },
      clearSelectedGroup() {
        this.accessCheckGroup = []
        this.selectedGroup = ''
      },
      getMenuItem() {
        getMenuAccess().then(response => {
          this.menus = response.data
        }).catch(() => {
          this.$Message.error('获取菜单列表出错')
        })
      },
      getGroups() {
        getGroups().then(response => {
          this.groups = response.data
        })
      },
      changeSelectedGroup(selectedGroup) {
        if (selectedGroup) {
          this.accessCheckGroup = this.groups.filter(item => item.id === selectedGroup)[0].operation
        }
      },
      showAddGroup() {
        this.addGroupVisible = true
      },
      closeAddGroup() {
        this.addGroupVisible = false
        this.newGroupName = ''
      },
      submitAddGroup() {
        this.submitAddGroupLoading = true
        const addGroupParam = {
          groupName: this.newGroupName
        }
        addGroup(addGroupParam).then(response => {
          this.submitAddGroupLoading = false
          if (response.status === 200) {
            this.$Message.success('添加权限组成功')
            this.closeAddGroup()
          } else {
            this.$Message.error('添加权限组失败:' + response.message)
          }
        }).catch(() => {
          this.submitAddGroupLoading = false
          this.$Message.error('位置错误')
        })
      },
      showAddPassport() {
        this.addPassportVisible = true
      },
      closeAddPassport() {
        this.addPassportVisible = false
        this.newUserName = ''
        this.newPwd = ''
        this.selectedGroup = ''
        this.newUserBaned = 1
      },
      submitAddPassport() {
        this.submitAddPassportLoading = true
        const passport = {
          accountName: this.newUserName,
          password: this.newPwd,
          groupId: this.selectedGroup,
          useAble: this.newUserBaned
        }
        addUser(passport).then(response => {
          this.submitAddPassportLoading = false
          if (response.status === 200) {
            this.$Message.success('添加用户成功')
            this.closeAddPassport()
            this.reloadList()
          } else {
            this.$Message.error('添加用户失败:' + response.message)
          }
        }).catch(() => {
          this.submitAddPassportLoading = false
        })
      },
      showChangePwd() {
        this.changePwdVisible = true
      },
      closeChangePwd() {
        this.changePwdVisible = false
        this.oldPwd = ''
        this.newPwd = ''
        this.newPwdConfirm = ''
      },
      submitChangePwd(account) {
        if (this.newPwd !== this.newPwdConfirm) {
          this.$Message.error('两次输入密码不一致!')
          return
        }
        console.log(account)
        const changePwdTO = {
          account: account,
          oldPwd: this.oldPwd,
          newPwd: this.newPwd
        }
        updatePwd(changePwdTO).then(response => {
          this.submitAddGroupLoading = false
          if (response.status === 200) {
            this.$Message.success('修改密码成功')
            this.closeChangePwd()
          } else {
            this.$Message.error('修改密码失败:' + response.message)
          }
        }).catch(() => {
          this.submitAddGroupLoading = false
          this.$Message.error('未知错误')
        })
      }
    },
    mounted() {
      this.initData()
    }
  }
</script>

<style scoped>
  .top-button {
    margin-right: 5px;
  }

  .top-button-group {
    margin-bottom: 5px;
  }
</style>
